<script lang="ts" setup>
import { postQRCodeApi, postMakeNowApi, postReplaceApi } from '@/services/goods'
import { useDeviceStore, useOrderStore } from '@/stores'
import type { equipmentOrderType, orderDetailType } from '@/types/goods'
import { onShow } from '@dcloudio/uni-app'
import { ref, computed, watch, inject } from 'vue'
import { MyShowModal, PageSkip, SwitchingTime, Toast } from '@/utils/tools'

const orderStore = useOrderStore()
const deviceStore = useDeviceStore()
const props = defineProps<{
  spotBox: equipmentOrderType
  isTriggered?: boolean
}>()

const status = computed(() => props.spotBox.status)
const operationalOnlineStatus = computed(() => props.spotBox.operationalOnlineStatus)
const machineType = computed(() => props.spotBox.machineType)
const scannedStatus = computed(() => props.spotBox.scannedStatus)
const orderType = computed(() => props.spotBox.orderType)
const endTime = computed(() => SwitchingTime(props.spotBox.endTime, '年月日'))
/**
 * 立即制作
 * * status 制作状态
 */
const onMakeNow = async () => {
  uni.showLoading({
    title: '加载中···',
    mask: true,
  })
  try {
    const res = await postMakeNowApi({ orderId: props.spotBox.orderId })
    uni.hideLoading()
    if (res.code === 200) {
      PageSkip(`/pagesGoods/goodsDetails/goodsDetails?orderId=${props.spotBox.orderId}`)
    } else {
      Toast(res.msg)
    }
  } catch (error) {
    uni.hideLoading()
  }
}
/**
 * * 监听订单列表状态的改变、父组件传来的值props.isTriggered 是否处于下拉刷新当中
 */
watch([() => props.isTriggered, () => orderStore.orderStatus], (newVal, oidVal) => {
  if (newVal[0] === true || newVal[1] === 'AwaitPackage') {
    changeDataFn()
  }
})
onShow(() => {
  if (props.spotBox.status === 'AwaitPackage' || props.spotBox.status === '') {
    changeDataFn()
  }
})

/**
 * 制作按钮和代取按钮的展示
 */
const isButtonShow = computed(() => {
  return props.spotBox.cupboardState === 0 && props.spotBox.replacementState === 0 ? true : false
})

const isCreationStatus = computed(() => {
  return props.spotBox.orderDetailList.every((item) => item.status === 'WaitingToBeMade')
})
// watch(
//   () => props.spotBox.orderDetailList.length,
//   () => {
//     if (props.spotBox.orderDetailList.length === 1) {
//       selectList.value = props.spotBox.orderDetailList // 当套餐只有一份的时候，就自动选中
//     }
//   },
//   {
//     deep: true,
//     immediate: true,
//   },
// )
/**
 * * 重置多选列表
 */
let selectList = ref<orderDetailType[]>([])
function changeDataFn() {
  selectList.value = []
  if (status.value !== 'AwaitPackage') {
    iconAll.value = 't-icon t-icon-a-18jinzhixuanzhong'
  } else {
    iconAll.value = 'iconfont icon_weixuanzhong'
  }
}
defineExpose({
  changeDataFn,
})
// 点击全选
let iconAll = ref('iconfont icon_weixuanzhong') // iocn

watch(
  () => status.value,
  (newVal) => {
    if (newVal !== 'AwaitPackage') {
      iconAll.value = 't-icon t-icon-a-18jinzhixuanzhong'
    }
  },
  { immediate: true },
)

// 选中列表
const onAllFn = () => {
  if (props.spotBox.status !== 'AwaitPackage') return // 判断点击的套餐状态是不是待取餐，是的话，直接退出去
  if (
    iconAll.value === 'iconfont icon_weixuanzhong' &&
    selectList.value.length !== props.spotBox.orderDetailList.length
  ) {
    iconAll.value = 'iconfont icon-checked' // 修改icon图标
    props.spotBox.orderDetailList.forEach((item) => {
      // 旧列表的每一项都不存在于新列表，
      if (!selectList.value.includes(item)) {
        selectList.value.push(item) // 就把每一项 push 进新列表
      }
    })
  } else {
    iconAll.value = 'iconfont icon_weixuanzhong'
    selectList.value = []
  }
}
/**
 * * 点击套餐内的单选按钮
 */
const onItem = (i: orderDetailType) => {
  if (props.spotBox.status !== 'AwaitPackage') return // 判断点击的套餐状态是不是待取餐，是的话，直接退出去
  if (!selectList.value.includes(i)) {
    console.log('进入添加')
    selectList.value?.push(i) // 当前套餐不存在，push 进去
    if (selectList.value.length === props.spotBox.orderDetailList.length) {
      iconAll.value = 'iconfont icon-checked' //
    }
    // console.log(JSON.parse(JSON.stringify(selectList.value)))
  } else {
    console.log('进入删除')
    let index = selectList.value.indexOf(i) // 求出当前套餐所在位置，
    selectList.value.splice(index, 1) // 删除当前套餐
    if (selectList.value.length !== props.spotBox.orderDetailList.length) {
      iconAll.value = 'iconfont icon_weixuanzhong'
    }
  }
}
watch(
  () => selectList.value,
  () => {
    if (selectList.value.length === props.spotBox.orderDetailList.length) {
      iconAll.value = 'iconfont icon-checked'
    }
  },
  { deep: true },
)
/**
 *  实付价格
 */
const paidPrice = computed(() => {
  return props.spotBox.orderDetailList.reduce((prev: number, next: orderDetailType) => {
    return prev + parseFloat(next.deviceAmount) * next.count
  }, 0)
})

/**
 *  计算总数量
 */
const sum = computed(() => {
  return props.spotBox.orderDetailList.reduce((prev: number, next: orderDetailType) => {
    return prev + next.count
  }, 0)
})
/**
 *  取餐码上传的数组
 */
const packageList = computed(() => {
  return selectList.value.map((item) => {
    return {
      orderDetailId: item.orderDetailId,
    }
  })
})

/**
 *  点击取餐码
 */
const takeFoodFun = async () => {
  if (packageList.value.length <= 0) return Toast(`请选择 "制作完成"或者\n"等待制作" 的套餐取餐`)
  const codeParm = { orderId: props.spotBox.orderId, packageList: packageList.value! }
  const res = await postQRCodeApi(codeParm)
  // console.log(res)
  if (res && res.data && res.code === 200) {
    console.log('点击取餐')
    codeOpen(res.data)
  } else {
    Toast(res.msg || `请选择正确的套餐取餐`)
  }
}

/**
 * *  跳转到详情页
 */
const skipToDetails = (orderId: string, goodsType: number) => {
  if (goodsType !== 2) {
    PageSkip(`/pagesGoods/goodsDetails/goodsDetails?orderId=${orderId}`)
  } else {
    PageSkip(`/pagesGoods/goodsDetails/goodsDetails?orderId=${orderId}&type=couponPack`)
  }
}
/**
 *  订单创建时间
 */
const oldDate = new Date(props.spotBox.createTime).getTime()
/**
 *  跳转到吃饭页面
 */
function skiEatPageFn(i: equipmentOrderType) {
  console.log(i)
  if (i.deviceInfo.businessStatus !== '运营中') return Toast('设备不在营业中')
  const deviceInfoItem = {
    ...i.deviceInfo,
    machineId: i.machineId,
    machineName: i.machineName,
    machineType: i.machineType,
  }
  deviceStore.setDeviceInfo(deviceInfoItem)
  PageSkip('/pages/eat/eat', 'switchTab')
}

/**点击代取触发 */
const replace = () => {
  MyShowModal('您确定要代取吗？').then(async (success: UniApp.ShowModalRes) => {
    if (success.confirm) {
      uni.showLoading({
        title: '加载中···',
        mask: true,
      })
      try {
        const res = await postReplaceApi({ orderId: props.spotBox.orderId })
        uni.hideLoading()
        if (res.code === 200) {
          PageSkip(`/pagesGoods/goodsDetails/goodsDetails?orderId=${props.spotBox.orderId}`)
        } else {
          Toast(res.msg)
        }
      } catch (error) {
        uni.hideLoading()
      }
    }
  })
}
const { codeOpen }: any = inject('deepParams')
</script>

<template>
  <view class="spotBox">
    <!-- 设备名称 -->
    <view class="headName">
      <view class="all" style="margin-right: 16rpx" :class="iconAll" @tap="onAllFn"> </view>
      <view @tap="skiEatPageFn(props.spotBox)" url="/pages/eat/eat" class="spotName">{{
        props.spotBox.machineName
      }}</view>
      <view @tap="skiEatPageFn(props.spotBox)" class="leftArrow iconfont icon_arrow-left-1"></view>
      <view class="orderStore" :class="{ activeStatus: props.spotBox.status === 'AwaitPackage' }">{{
        props.spotBox.status === 'AwaitPackage'
          ? '待取餐'
          : props.spotBox.status === 'ToBePaid'
          ? '待支付'
          : props.spotBox.status === 'Canceled'
          ? '已取消'
          : props.spotBox.status === 'Refund'
          ? '已退款'
          : props.spotBox.status === 'Finish'
          ? '已完成'
          : props.spotBox.status === 'APPLY_REFUND'
          ? '退款中'
          : '订单异常'
      }}</view>
    </view>
    <!-- 套餐信息盒子 -->
    <view class="itemBox">
      <!-- 套餐item -->
      <view
        class="setMealItem"
        v-for="item in props.spotBox.orderDetailList"
        :key="item.orderDetailId"
        @tap="skipToDetails(props.spotBox.orderId, props.spotBox.goodsType)"
      >
        <view class="status" v-if="props.spotBox.status === 'AwaitPackage'"
          >{{
            item.status === 'WaitingToBeMade'
              ? '等待制作'
              : item.status === 'MadeDone'
              ? '制作完成'
              : item.status === 'InTheMaking'
              ? '正在制作'
              : item.status === 'MakeExceptions'
              ? '制作异常'
              : item.status === 'PickupIsComplete'
              ? '取餐完成'
              : ''
          }}
        </view>
        <view class="subsetItem">
          <view
            class="iconItem"
            :class="{
              'iconfont icon_weixuanzhong': !selectList.includes(item) && status === 'AwaitPackage',
              'iconfont icon-checked': selectList.includes(item) && status === 'AwaitPackage',
              't-icon t-icon-a-18jinzhixuanzhong': props.spotBox.status !== 'AwaitPackage',
            }"
            @tap.stop="onItem(item)"
          >
          </view>
          <image
            class="image"
            :src="item.thumbUrl + '?x-oss-process=image/resize,h_300,m_lfit'"
            mode="scaleToFill"
          />
          <view class="argument">
            <view class="name">{{ item.packageName }}</view>
            <view class="style" v-if="props.spotBox.goodsType !== 2"
              >{{ item.packageName }} | 餐具</view
            >
          </view>
          <view class="priceNumber">
            <view class="price"
              ><text class="icon">￥</text>{{ Number(item.deviceAmount).toFixed(2) }}</view
            >
            <view class="number"> × {{ item.count }} </view>
          </view>
        </view>
        <view class="tipsText">
          <view class="tips" v-if="props.spotBox.status === 'AwaitPackage'">
            <view>请在</view>
            <view class="red">
              {{
                orderType === '2'
                  ? `${endTime}${props.spotBox.deviceInfo.saleEndTime}`
                  : `今日${props.spotBox.deviceInfo.saleEndTime}`
              }}
            </view>
            <view>前完成取餐</view>
          </view>
        </view>
      </view>
    </view>
    <view class="goodsTime">
      <view class="date">
        <uni-dateformat :date="oldDate" format="yyyy-MM-dd hh:mm:ss"> </uni-dateformat>
      </view>
      <view class="number">
        <view class="number_1">共{{ sum }}件</view>
        <view class="number_2"
          >￥{{ orderType === '2' ? paidPrice : Number(spotBox.price).toFixed(2) }}</view
        >
      </view>
    </view>
    <view class="floorButton">
      <button
        v-if="
          status === 'AwaitPackage' &&
          machineType === 3 &&
          isButtonShow &&
          !scannedStatus &&
          isCreationStatus
        "
        hover-class="is-hover"
        class="locker"
        @tap="onMakeNow()"
      >
        做好存柜
      </button>
      <button
        v-if="
          status === 'AwaitPackage' &&
          operationalOnlineStatus &&
          isButtonShow &&
          !scannedStatus &&
          isCreationStatus
        "
        hover-class="is-hover"
        class="replace"
        @tap="replace()"
      >
        客服代取
      </button>
      <button
        hover-class="is-hover"
        class="code"
        v-if="status === 'AwaitPackage' && isButtonShow && !scannedStatus"
        @tap="takeFoodFun()"
      >
        取餐码
      </button>
    </view>
  </view>
</template>

<style lang="scss">
.spotBox {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx 24rpx 28rpx;
  margin-bottom: 20rpx !important;
  box-shadow: 0rpx 4rpx 198rpx 2rpx rgba(0, 0, 0, 0.05);
}
.icon-checked {
  color: $uni-color-motif !important;
}
// 设备名称
.headName {
  display: flex;
  align-items: center;
  height: 36rpx;
  .all {
    color: #0000004d;
    font-size: 32rpx;
  }
  .spotName {
    font-size: 28rpx;
    margin: 0 16rpx 0 0;
    color: #212121;
    font-weight: 600;
  }
  .leftArrow {
    font-size: 20rpx;
  }
  .orderStore {
    flex: 1;
    font-size: 26rpx;
    text-align: right;
  }
  .activeStatus {
    color: #ffaa2c;
  }
}
// 套餐 div
.itemBox {
  margin: 24rpx 0 0;
}
// 套餐 item
.setMealItem {
  font-size: 22rpx;
  box-sizing: border-box;
  .status {
    text-align: right;
    color: #00000080;
  }
  .subsetItem {
    display: flex;
    align-items: center;
    height: 176rpx;
    margin: 8rpx 0;
    background-color: #f8f8f8;
    padding: 24rpx 20rpx 24rpx 10rpx;
    border-radius: 20rpx;
    .iconItem {
      font-size: 32rpx;
      z-index: 1;
    }
    .icon_weixuanzhong {
      color: #0000004d;
    }
    .image {
      width: 120rpx;
      height: 120rpx;
      margin: 0 20rpx;
      border-radius: 8rpx;
    }
    .argument {
      flex: 1;
      margin-right: 20rpx;
      display: flex;
      flex-direction: column;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 显示省略号 */
      text-align: left;
      .name {
        font-size: 30rpx;
        color: #000000e5;
        margin-bottom: 8rpx;
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
      .style {
        font-size: 22rpx;
        color: #ccc;
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
    }
    .priceNumber {
      display: flex;
      flex-direction: column;
      text-align: right;
      font-size: 22rpx;
      color: #0000004d;
      .price {
        font-size: 28rpx;
        color: #000;
        .icon {
          color: $uni-color-motif;
        }
      }
    }
  }
  .tipsText {
    // height: 56rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tips {
      color: #00000080;
      display: flex;
      .red {
        color: #fa5151;
      }
    }
  }
}
// 订单时间
.goodsTime {
  display: flex;
  justify-content: space-between;
  margin: 12rpx 0;
  height: 36rpx;
  font-size: 24rpx;
  color: #00000080;
  .number {
    display: flex;
    align-items: center;
    .number_2 {
      font-size: 26rpx;
      color: #000000e5;
    }
  }
}

.floorButton {
  display: flex;
  justify-content: flex-end;
  margin-top: 24rpx;
  // 取餐码
  .replace,
  .locker,
  .code {
    line-height: 56rpx;
    height: 56rpx;
    padding: 0 24rpx;
    margin: 0;
    margin-left: 18rpx;
    font-size: 24rpx;
    color: #333;
    background-color: #fdcb4a;
    border-radius: 28rpx;
    box-sizing: border-box;
  }
  .is-hover {
    color: rgba(255, 255, 255, 0.6);
    opacity: 0.7;
  }
}
.t-icon-a-18jinzhixuanzhong {
  width: 28rpx;
  height: 28rpx;
}
</style>
